package nc.ui.arap.view;

import nc.ui.pub.ButtonObject;
import nc.ui.pub.ClientEnvironment;
import nc.ui.pub.ToftPanel;
import nc.ui.pub.bill.BillEditListener;
import nc.ui.pub.bill.BillListPanel;
import nc.vo.arap.exception.ExceptionHandler;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;

public abstract class BatchTableView<T> extends ToftPanel implements ViewContext<T> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8421197736568888461L;
	
	private BillListPanel listPanel;
	
	protected ViewState<T> state;
	
	public abstract Controler<T> getControler();
	
	public abstract BillEditListener getBillEditListener();
	
	public abstract ViewState<T> getInitViewState();
	
	public BatchTableView() {
		super();
		setSize(774, 419);
		add(getListPanel(), "Center");
		setButtons(getButtonObjects());
		try {
			getBatchTabelModel().init();
		} catch (BusinessException e) {
			ExceptionHandler.consume(e);
			showErrorMessage(e.getMessage());
		}
		getListPanel().setHeaderValueVO((CircularlyAccessibleValueObject[]) getBatchTabelModel().getData());
		setViewState(getInitViewState());
	}
	
	public BillListPanel getListPanel() {
		if (listPanel == null) {
			listPanel = new BillListPanel();
			listPanel.loadTemplet(getBillType(), null, ClientEnvironment.getInstance().getUser().getPrimaryKey(),
					ClientEnvironment.getInstance().getCorporation().getPk_corp());
			listPanel.addEditListener(getBillEditListener());
			listPanel.setMultiSelect(true);
		}
		
		return listPanel;
	}
	
	@Override
	public void onButtonClicked(ButtonObject bo) {
		 try {
			getControler().handle(bo, this);
		} catch (BusinessException e) {
			ExceptionHandler.consume(e);
			showErrorMessage(e.getMessage());
		}
	}
	
	protected abstract String getBillType();
	
	protected abstract ButtonObject[] getButtonObjects();
	
	public ButtonObject getButtonObject(String code) {
		return getButtonObjectByCode(code);
	}
	
	public void setViewState(ViewState<T> state) {
		this.state = state;
		this.state.handleButtons(this);
		this.state.handleView(this);
		updateButtons();
	}
	

	public void synchronizeMode() {
		T[] data = getBatchTabelModel().getData();
		getListPanel().getHeadBillModel().setBodyDataVO((CircularlyAccessibleValueObject[]) data);
	}

	public void synchronizeModel(int row) {
		if (getListPanel().getHeadBillModel().getRowCount() <= row) {
			for (int i = getListPanel().getHeadBillModel().getRowCount() - 1; i < row; i ++) {
				getListPanel().getHeadBillModel().addLine();
			}
			
		}
		getListPanel().getHeadBillModel().setBodyRowVO((CircularlyAccessibleValueObject) getBatchTabelModel().getSelectData(), row);
	}

}
